package com.liu.vueblog.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liu.vueblog.common.lang.Result;
import com.liu.vueblog.entity.Blog;
import com.liu.vueblog.service.BlogService;
import com.liu.vueblog.utils.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LiuXin
 * @since 2021-06-17
 */
@RestController
@RequestMapping("/vueblog")
public class BlogController {

    @Resource
    BlogService blogService;

    /**
     * 查看所有
     * @param currentPage
     * @return
     */
    @RequestMapping(path = "/blogs", method = RequestMethod.GET)
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage){
        Page page = new Page(currentPage, 5);
        QueryWrapper<Blog> wrapper = new QueryWrapper<Blog>().orderByDesc("created");
        IPage pageData = blogService.page(page, wrapper);
        return Result.success(pageData);
    }

    /**
     * 查看其中一个
     * @param id
     * @return
     */
    @RequestMapping(path = "/blog/{id}", method = RequestMethod.GET)
    public Result detail(@PathVariable(name = "id") Long id){
        Blog blog = blogService.getById(id);
        Assert.notNull(blog,"该博客已被删除");
        return Result.success(blog);
    }

    /**
     * 编辑，添加
     * @param blog
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(path = "/blog/edit", method = RequestMethod.POST)
    public Result edit(@Validated @RequestBody Blog blog){

        Blog temp = null;
        //只能编辑自己的文章
        if (blog.getId() != null) {
            temp = blogService.getById(blog.getId());
            System.out.println(ShiroUtils.getProfile().getId());
            Assert.isTrue(temp.getUserId().longValue() == ShiroUtils.getProfile().getId().longValue(), "没有权限修改");
        } else {
            //添加新文章
            temp = new Blog();
            temp.setUserId(ShiroUtils.getProfile().getId());
            temp.setCreated(LocalDateTime.now());
            temp.setStatus(0);
        }

        BeanUtil.copyProperties(blog,temp,"id", "userId", "created", "status");
        blogService.saveOrUpdate(temp);
        return Result.success(null);
    }
}
